package week13.week_13_server;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.security.KeyStore;
import javax.net.ssl.*;

public class MyCommServer {
	/**
	 * @param args
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException, IOException {
		RegisterProcessor();
	}

	/**
	 * 启动UDPSocket端口，用于处理客户端的聊天信息
	 */
	public static void dataProcessor(){
		SocketAddress sa = new InetSocketAddress(ServerInfo.serverAddr,ServerInfo.serverDataPort);
		try (DatagramSocket s = new DatagramSocket(sa)){
			System.out.println("Data server is listening on" + ServerInfo.serverAddr+ ":" + ServerInfo.serverDataPort +"...");
			while (true){
				try {
					DatagramPacket pin = new DatagramPacket(new byte[512],512);
					s.receive(pin);
					String msg = new String(pin.getData(),0, pin.getLength());
					System.out.println(msg);

					String replyMsg = "echo: " + msg;
					DatagramPacket pout  = new DatagramPacket(
							replyMsg.getBytes(),replyMsg.getBytes().length,pin.getAddress(),pin.getPort());
					s.send(pout);
					System.out.println(pin.getAddress()+":"+pin.getPort());

				}catch (IOException ex) {
					System.out.println("异常信息："+ex.getMessage());
				}
			}

		} catch (IOException ex) {
			System.out.println("异常信息："+ex.getMessage());
		}

	}
	/**
	 * 用于处理用户的注册与登录
	 */
	public static void RegisterProcessor() {
		// TODO Auto-generated method stub
		SSLServerSocket serverSocket = null;
		try{

			//获取jks类型的密钥库，ks保存本主机的公钥和私钥的密钥库,tks是保存来访者的公钥的密钥库
			KeyStore ks = KeyStore.getInstance("JKS");//本机的密钥库
			KeyStore tks = KeyStore.getInstance("JKS");//可信任的其它来访主机的公钥库

			//加载密钥库文件，需要提供口令
			ks.load(new FileInputStream(ServerInfo.keyStorePath),ServerInfo.password_ks.toCharArray());
			tks.load(new FileInputStream(ServerInfo.trustStorePath),ServerInfo.password_ts.toCharArray());

			//为相应的密钥库创建一个KeyManagerFactory，TrustManagerFactory
			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

			kmf.init(ks,ServerInfo.password_pk.toCharArray());
			tmf.init(tks);

			//为使用的算法创建一个SSLContext
			SSLContext  context = SSLContext.getInstance("SSL");

			context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
			//context.init(kmf.getKeyManagers(),null,null);//如果服务器不需要验证客户端，则可以不用初始化可信任的密钥库,后面的setNeedClientAuth要设置为false;

			SSLServerSocketFactory factory = context.getServerSocketFactory();
			SocketAddress address = new InetSocketAddress(ServerInfo.serverAddr, ServerInfo.serverPort);
			serverSocket =(SSLServerSocket)factory.createServerSocket();
			serverSocket.bind(address);

			serverSocket.setNeedClientAuth(true);//如果设置为false,是不需要验证客户端
			System.out.println("Server is running and listening...");

			while (true){
				try{
					Socket	socket = serverSocket.accept();
					new MyCommThread(socket).start();
				}catch (IOException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}catch (Exception e) {
			// TODO: handle exception
			if(serverSocket!=null){
				try {
					serverSocket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			e.printStackTrace();
		}
	}

}
